#include "drawarea.h"
#include <QPaintEvent>

DrawArea::DrawArea(QWidget *parent) : QWidget{parent}
{
    setAttribute(Qt::WA_StyledBackground, true);
}

int DrawArea::getSortType() const
{
    return sortType;
}

SortBase *DrawArea::getSortMethod() const
{
    return sortMethod;
}

void DrawArea::setSortMethod(int type, SortBase *obj)
{
    if (sortType == type) {
        return;
    }

    // delete previous sortMethod
    if (sortMethod) {
        sortMethod->deleteLater();
        sortMethod = nullptr;
    }

    sortType = type;
    sortMethod = obj;

    if (sortMethod) {
        connect(sortMethod, &SortBase::updateRequest, this, [this] { update(); });
        connect(sortMethod, &SortBase::runStateChanged, this, &DrawArea::runStateChanged);
    }

    update();
}

void DrawArea::start(int count, int interval)
{
    if (sortMethod)
        sortMethod->sort(count, interval);
}

void DrawArea::stop()
{
    if (sortMethod)
        sortMethod->stop();
}

void DrawArea::skip()
{
    if (sortMethod)
        sortMethod->skip();
}

void DrawArea::paintEvent(QPaintEvent *event)
{
    event->accept();

    QPainter painter(this);
    painter.fillRect(rect(), Qt::black);

    if (sortMethod) {
        sortMethod->draw(&painter, width(), height());
    }
}
